package com.ruoyi.common.utils.file;

import com.ruoyi.common.constant.UserConstants;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class AmzFileUtils {

    private static final String websit = "http://hubelf.s3-website.ap-south-1.amazonaws.com/";

    public static String upload(String fileName, File file) {
        Region region = Region.AP_SOUTH_1;
        String bucketName = "hubelf";
        S3Client s3 = S3Client.builder()
                .region(region)
                .credentialsProvider(new AwsCredentialsProvider() {
                    @Override
                    public AwsCredentials resolveCredentials() {
                        return new AwsCredentials() {
                            @Override
                            public String accessKeyId() {
                                return UserConstants.accessKeyId;
                            }
                            @Override
                            public String secretAccessKey() {
                                return UserConstants.secretAccessKey;
                            }
                        };
                    }
                })
                .build();
        try {
            Map<String, String> metadata = new HashMap<>();
            metadata.put("x-amz-meta-auth", "hubelf");
            PutObjectRequest putOb = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(fileName)
                    .metadata(metadata)
                    .build();
            s3.putObject(putOb, RequestBody.fromFile(file));
        } catch (S3Exception e) {
            e.printStackTrace();
        }finally {
            file.delete();
            s3.close();
        }
        return websit+fileName;
    }
}
